package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"
	"we-chat-mgr/models/cache"
	"we-chat-mgr/models/mysql"

	"we-chat-mgr/wechatrpc/internal/svc"
	"we-chat-mgr/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type WeChatMomentsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWeChatMomentsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WeChatMomentsListLogic {
	return &WeChatMomentsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *WeChatMomentsListLogic) WeChatMomentsList(in *wechatrpc.WeChatMomentsListRequest) (*wechatrpc.WeChatMomentsListResponse, error) {
	// todo: add your logic here and delete this line

	var finduser mysql.User
	err := finduser.FindUserByUserId(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("用户不存在")
	}

	var momentsList []*wechatrpc.WeChatMomentsList
	key := fmt.Sprintf("momentsList_%s", in)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()
	if cacheData == "" {
		momentsList = mysql.WeChatMomentsList(mysql.DB, in)
		jsonData, _ := json.Marshal(momentsList)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute*5)
	} else {
		json.Unmarshal([]byte(cacheData), &momentsList)
	}

	return &wechatrpc.WeChatMomentsListResponse{
		List: momentsList,
	}, nil
}
